#include "widget.h"
#include "ui_widget.h"
#include <QVBoxLayout>
#include <QTimer>
#include <QBuffer>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrlQuery>

#include <QSslSocket>
#include <QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("上班打卡");


    if (QSslSocket::supportsSsl()) {
           qDebug() << "SSL Library Build Version:" << QSslSocket::sslLibraryBuildVersionString();
           qDebug() << "SSL Runtime Version:" << QSslSocket::sslLibraryVersionString();
       } else {
           qDebug() << "SSL is not supported by this Qt build.";
       }

    camera = new QCamera(this);
    capture = new QCameraImageCapture(camera,this);
    viewfinder = new QCameraViewfinder(this);
    showMaximized();

    ui->w_camera->setFixedSize(500,360);
    ui->w_camera->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    viewfinder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QVBoxLayout *layout = new QVBoxLayout; // 创建一个垂直布局
    layout->addWidget(viewfinder); // 将 viewfinder 添加到布局中
    ui->w_camera->setLayout(layout); // 将布局设置到父 QWidget 中
    ui->w_camera->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    camera->setCaptureMode(QCamera::CaptureStillImage);
    camera->setViewfinder(viewfinder);
    camera->start();
    // 启动定时器，每隔指定时间捕获一次图像
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::captureImage);
    timer->start(5000); // 每1秒捕获一次图像，可以根据需要调整时间间隔
    // 连接图像捕捉信号到槽函数
    connect(capture, &QCameraImageCapture::imageCaptured, this, &Widget::processCapturedImage);



    //连接信号与槽
    connect(this, &Widget::accessTokenReady, this, &Widget::onAccessTokenReceived);
    connect(this, &Widget::faceDetected, this, &Widget::onFaceDetected);
    connect(this, &Widget::faceSearched, this, &Widget::onFaceSearched);


}

Widget::~Widget()
{
    delete ui;
}


void Widget::captureImage()
{
    // 捕获图像
    capture->capture();
}

void Widget::processCapturedImage(int id, const QImage &preview)
{
    qDebug() << "Image captured with ID:" << id;

    // 将捕获的图像保存或处理
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    preview.save(&buffer, "JPG");  // 将图像保存到缓冲区
    this->capturedImage = byteArray.toBase64();  // 转换为Base64编码

    //获取token
    getAccessToken();
}
void Widget::getAccessToken()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    // 百度API的URL，用于获取access_token
    QString url = "https://aip.baidubce.com/oauth/2.0/token";
    QUrl requestUrl(url);
    // 构建POST请求参数
    QUrlQuery query;
    query.addQueryItem("grant_type", "client_credentials");
    query.addQueryItem("client_id", "KtViX4PuhNr8hdOvWMVpDWkt");  // 替换为你的API Key
    query.addQueryItem("client_secret", "wcizqXnPH8bxPQLu6oyRZk7hDKrn2Nos");  // 替换为你的Secret Key
    requestUrl.setQuery(query);

    QNetworkRequest request(requestUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    // 发送POST请求
    QNetworkReply *reply = manager->post(request, QByteArray());
    qDebug() << "token request start  111";

    // 处理返回结果
    connect(reply, &QNetworkReply::finished, [=]() {
                if (reply->error() == QNetworkReply::NoError) {
                    qDebug() << "token response success 222";
                    QByteArray response_data = reply->readAll();

                    // 解析JSON响应
                    QJsonDocument jsonDoc = QJsonDocument::fromJson(response_data);
                    QJsonObject jsonObj = jsonDoc.object();
                    //保存token
                    this->access_token = jsonObj["access_token"].toString();
                    qDebug() << "token get success 333";
                    // 获取Access Token成功，发射信号
                    emit accessTokenReady();
                    qDebug() << "token signal success 444";

                } else {
                    qDebug() << "Error:" << reply->errorString();
                }
                reply->deleteLater();
            });
}
void Widget::onAccessTokenReceived()
{
    // Access Token获取成功后，进行人脸检测
    detectFace(capturedImage);
}
void Widget::detectFace(const QByteArray &base64Image)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QString url = QString("https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=%1").arg(this->access_token);
    QNetworkRequest request((QUrl(url)));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    //创建jason请求体

    // 创建JSON请求体
    QJsonObject json;
    json["image"] = QString::fromLatin1(base64Image);
    json["image_type"] = "BASE64";
    json["face_field"] = "age,qu,genderality";  // 请求返回年龄、性别和质量信息
    json["max_face_num"] = 1;  //测一 只检张脸
    json["face_type"] = "LIVE";  // 活体检测

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

       // 发送POST请求
    QNetworkReply *reply = manager->post(request, data);
    qDebug() << "dedetect request start  111";
    connect(reply, &QNetworkReply::finished, [=]() {
           if (reply->error() == QNetworkReply::NoError) {
               QByteArray response_data = reply->readAll();
               qDebug() << "dedetect response success  222";

               // 处理人脸检测的结果，进行下一步操作
               int ret = processFaceDetectionResponse(response_data);
               // 发射信号，通知人脸检测完成
               emit faceDetected(ret);
               qDebug() << "dedetect signal success  333";
           } else {
               qDebug() << "Face detection failed: " << reply->errorString();
           }
           reply->deleteLater();
       });

}
int Widget::processFaceDetectionResponse(const QByteArray &response_data)
{
    // 解析人脸检测的JSON响应，并检查是否检测到人脸
    QJsonDocument doc = QJsonDocument::fromJson(response_data);
    QJsonObject obj = doc.object();

    // 获取 result 对象
    QJsonObject resultObj = obj["result"].toObject();
    int face_num = resultObj["face_num"].toInt();
    if (face_num > 0) {
        qDebug() << "detach success 444!";
        return 1;
    } else {
        qDebug() << "no detach";
        return 0;
    }
}
void Widget::onFaceDetected(int result)
{
    if (result == 1) {
        qDebug() << "detected success!";
        // 人脸检测成功后，进行人脸搜索
        searchFace(capturedImage);
    } else {
        qDebug() << "No face detected.";
    }
}

int Widget::searchFace(const QByteArray &base64Image)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QString url = QString("https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=%1").arg(this->access_token);
    QNetworkRequest request((QUrl(url)));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");

    // 创建JSON请求体
    QJsonObject json;
    json["image"] = QString::fromLatin1(base64Image);
    json["image_type"] = "BASE64";
    json["group_id_list"] = "face_client";  // 你的人脸库ID，替换为你实际的ID
    json["quality_control"] = "NORMAL";
    json["liveness_control"] = "LOW";
    json["max_user_num"] = 1;  // 返回匹配度最高的一个用户
    json["match_threshold"] = 80;  // 设置匹配阈值，80是推荐值

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    QNetworkReply *reply = manager->post(request,data);

    connect(reply, &QNetworkReply::finished, [=]() {
            if (reply->error() == QNetworkReply::NoError) {
                QByteArray response_data = reply->readAll();
                qDebug() << "Face search response:" << response_data;

                // 处理人脸搜索的结果
                int ret = processFaceSearchResponse(response_data);
                // 发射信号，通知人脸搜索完成
                emit faceSearched(ret);
            } else {
                qDebug() << "Face search failed: " << reply->errorString();
            }
            reply->deleteLater();
        });
    return 0;
}
int Widget::processFaceSearchResponse(const QByteArray &response_data)
{
    QJsonDocument doc  = QJsonDocument::fromJson(response_data);
    QJsonObject obj = doc.object();
    QJsonObject resultObj = obj["result"].toObject();
    QJsonArray userList = resultObj["user_list"].toArray();
    if (!userList.isEmpty())
    {
         QJsonObject user = userList[0].toObject();
         QString user_id = user["user_id"].toString();
         float score = user["score"].toDouble();
         qDebug() << "Matched user_id:" << user_id;
         qDebug() << "Match score:" << score;

         // 在这里可以处理匹配到的用户信息，例如显示在界面上
          if (score >= 80)
          {
                return 1;
          }
          else
          {
               qDebug() << "Low confidence in matching, might not be the correct user.";
          }
     }
    else
    {
            qDebug() << "No matching user found.";
     }
}

void Widget::onFaceSearched(int result)
{
    if (result == 1) {
        qDebug() << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!66666";
        ui->lb_access->setText("打卡成功");
    } else {
        qDebug() << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!000000";
        ui->lb_access->setText("打卡失败");
    }
}
